package com.muyu.common.core.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.muyu.common.core.basic.SecurityBasic;
import lombok.AllArgsConstructor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.Date;

/**
 * 框架字段自动填充器
 * @author dongzeliang
 * @version 1.0
 * @description: 框架字段自动填充器
 * @date 2025/3/1 11:51
 */
@AllArgsConstructor
@ConditionalOnProperty(value = "basic.mybatis-plus.meta.enabled", havingValue = "true")
public class SystemMetaObjectHandler implements MetaObjectHandler {

    private final SecurityBasic securityBasic;

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createBy", String.class, securityBasic.getUsername());
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        this.strictInsertFill(metaObject, "updateBy", String.class, securityBasic.getUsername());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
    }
}
